<?php

namespace App\Utils\WeChat;

use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Facades\Log;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

/**
 * 绒博汇
 */
class RbhMiniProgramWechat implements WeChat
{

    private string $appId = 'wx28de43953b90f5c8';
    private string $appSecret = 'ceb79d97d046c697f8332a903be2e9e7';

    private Application $app;

    /**
     * 构造实例
     * @throws InvalidArgumentException
     */
    public function __construct()
    {
        $this->app = new Application([
            'app_id' => $this->appId,
            'secret' => $this->appSecret,
            'token' => 'fCoJz5PV1ek2Lrh',
        ]);
    }

    /**
     * 获取小程序openid
     * @param $code
     * @return mixed|null
     * @throws ClientExceptionInterface
     * @throws DecodingExceptionInterface
     * @throws RedirectionExceptionInterface
     * @throws ServerExceptionInterface
     * @throws TransportExceptionInterface
     */
    public function getUserOpenId($code): mixed
    {
        $utils = $this->app->getUtils();
        try {
            $data = $utils->codeToSession($code);
            return $data['openid'];
        } catch (\Exception $e) {
            Log::error('获取小程序openid异常,' . $e->getMessage());
            return null;
        }
    }

    /**
     * 获取小程序手机号码
     * @param $code
     * @return null|mixed
     * @throws TransportExceptionInterface
     */
    public function getUserMobile($code): mixed
    {
        try {
            $responseString = $this->app->getClient()->postJson('wxa/business/getuserphonenumber', ['code' => $code]);
            return $this->getPhoneInfo($responseString);
        } catch (\Exception $e) {
            Log::error('获取小程序手机号码异常,' . $e->getMessage());
        }
        return null;
    }

    public function messageResponse()
    {
        // TODO: Implement messageResponse() method.
    }

    public function oauth()
    {
        // TODO: Implement oauth() method.
    }

    public function callback()
    {
        // TODO: Implement callback() method.
    }

    /**
     * @param $responseString
     * @return null|mixed
     */
    private function getPhoneInfo($responseString): mixed
    {
        $response = json_decode($responseString);
        if ($response->errcode == 0)
            return $response->phone_info;
        else {
            Log::error('获取小程序手机号码异常,' . $response->errmsg);
            return null;
        }
    }
}
